<?php

namespace app\api\controller\product;

use app\api\model\product\Car as CarModel;
use app\api\controller\Controller;
use app\api\model\product\VinLog;
use app\common\library\aipocr\AipOcr;
use app\common\model\product\CarQueryLog;
use lib\Http;
use lib\Liyang;
use think\facade\Cache;

/**
 * 商品分类控制器
 */
class Car extends Controller
{
    /**
     * 分类页面
     */
      public function index()
    {
        // 获取车型
        $data = $this->getData();
        $parentid = $data['parentid'] ?? 0;
        $targetDepth = isset($data['level']) ? (int)$data['level'] : null;
        
        // 初始化变量
        $car = [];
        
        // 如果有搜索值，始终搜索depth=4的数据
        if (!empty($data['searchValue'])) {
            // 构建搜索条件
            $searchWhere = [];
            
            // 始终搜索depth=4的数据
            $searchWhere[] = ['depth', '=', 4];
            
            // 创建查询构建器
            $query = CarModel::where($searchWhere);
            
            // 添加搜索条件 - 直接使用简单的like查询
            // MySQL默认是不区分大小写的，除非表的字段被特殊设置为binary
            if ($data['searchType'] == 1) {
                $query = $query->where('name', 'like', '%' . $data['searchValue'] . '%');
            } elseif ($data['searchType'] == 2) {
                $query = $query->where('engine', 'like', '%' . $data['searchValue'] . '%');
            } elseif ($data['searchType'] == 3) {
                $query = $query->where('chassis_code', 'like', '%' . $data['searchValue'] . '%');
            }
            
            // 执行查询
            $level4Results = $query->select()->toArray();
            // 如果需要显示特定层级的数据
            if (!is_null($targetDepth) && $targetDepth < 4) {
                // 保存层级4数据的ID，用于后续查询
                $level4Ids = array_column($level4Results, 'id');
                
                // 收集每个层级的父ID
                $parentIds = [];
                $currentIds = array_column($level4Results, 'parentid');
                
                // 从depth=4向上查找到指定层级
                $currentDepth = 3; // 从父级开始
                
                while ($currentDepth >= $targetDepth) {
                    if (empty($currentIds)) {
                        break;
                    }
                    
                    // 查找当前层级的所有项目
                    $parents = CarModel::where('id', 'in', $currentIds)
                        ->where('depth', $currentDepth)
                        ->select()
                        ->toArray();
                    
                    // 如果到达目标层级，保存这些ID
                    if ($currentDepth == $targetDepth) {
                        $parentIds = array_column($parents, 'id');
                        break;
                    }
                    
                    // 继续向上查找
                    $currentIds = array_column($parents, 'parentid');
                    $currentDepth--;
                }
                
                // 获取指定层级的数据
                if (!empty($parentIds)) {
                    $car = CarModel::where('id', 'in', $parentIds)
                        ->where('depth', $targetDepth)
                        ->select();
                }
            } else {
                // 返回depth=4的数据或基于parentid筛选
                if ($parentid > 0) {
                    // 如果是搜索模式，需要确保只返回符合搜索条件的车辆
                    if (!empty($data['searchValue'])) {
                        // 使用搜索结果中的ID，只返回符合条件的车辆
                        $level4Ids = array_column($level4Results, 'id');
                        $car = CarModel::where('id', 'in', $level4Ids)
                            ->where('parentid', $parentid)
                            ->select();
                    } else {
                        // 非搜索模式，显示所有parentid下的车辆
                        $car = CarModel::where('parentid', $parentid)
                            ->where('depth', 4)
                            ->select();
                    }
                } else {
                    // 当targetDepth == 4或未设置时，直接使用搜索结果
                    if (!empty($data['searchValue'])) {
                        // 直接使用搜索结果
                        $car = CarModel::where('id', 'in', array_column($level4Results, 'id'))->select();
                    } else {
                        // 非搜索模式下，如果是查看第4级但没有指定父ID，则不返回任何数据
                        // 因为第4级数据量可能很大
                        $car = [];
                    }
                }
            }
        } else {
            // 无搜索条件，正常显示当前父级下的子项
            $where['parentid'] = $parentid;
            
            // 如果指定了层级，则查询对应层级
            if (!is_null($targetDepth)) {
                $car = CarModel::where($where)
                    ->where('depth', $targetDepth)
                    ->select();
            } else {
                // 确定当前所在的深度级别
                $currentDepth = 0;
                if ($parentid > 0) {
                    $parent = CarModel::where('id', $parentid)->find();
                    if ($parent) {
                        $currentDepth = $parent['depth'];
                    }
                }
                
                // 下一级的深度
                $nextDepth = $currentDepth + 1;
                
                $car = CarModel::where($where)
                    ->where('depth', $nextDepth)
                    ->select();
            }
        }

        return $this->renderSuccess('', $car);
    }

    
    public function query()
    {
        $user = $this->getUser();

        list($result,$msg) = CarQueryLog::checkSearch($user->user_id);
        if(!$result) return $this->renderError('您的查询次数已用完，请联系供货商');


        $data = $this->postData();
        $vin = $data['vin'];
        //去掉车型后6位
        $vin_sub = substr($vin,0,11);
        $returnData =  VinLog::where('vin_sub',$vin_sub)->find();
        if (!$returnData) {
            $ret = Liyang::getPreciseCompressVin($vin);
            if($ret['code'] != 1){
                return $this->renderError($ret['msg']);
            }
            $returnData = $ret['data'];
            $returnData['app_id'] = $this->app_id;
            $returnData['vin'] = $vin;
            $returnData['vin_sub'] = $vin_sub;
            VinLog::create($returnData);
        }
        $returnData['carlist'] = CarModel::whereIn('ly_pid',explode(';',$returnData['levelIds']))->column('id,name');
// halt($returnData);
        if(empty($returnData['carlist'])){
            return $this->renderError('未获取到车型');
        }
        return $this->renderSuccess('', $returnData);
    }
    
    public function getVin()
    {
        $user = $this->getUser();

        list($result,$msg) = CarQueryLog::checkSearch($user->user_id);
        if(!$result) return $this->renderError('您的查询次数已用完，请联系供货商');
        // return $this->renderSuccess('', 'LS5A3DDE6GA011014');
        $image = $this->request->post('image');
//        $client = new AipOcr('119297161','XeKdNw4F7974JARHjKxG9ZCR','BOkfHeAx5SrPaQ9KJ9RjKBGI95SCWyvC');
//        $res = $client->vinCodeUrl($image);
        if(!$image){
            return $this->renderError('请上传图片');
        }
        // 获取图片二进制数据
        $imageData = file_get_contents($image);
        if ($imageData === false) {
            return $this->renderError('为加载到图片');
        }
        // 转换为 Base64
        $base64 = base64_encode($imageData);
        $ret = Liyang::getvinbyocr($base64);
        if($ret['code'] != 1 || $ret['data']['Info']['success'] == 'false'){
            return $this->renderError($ret['data']['Info']['details']??'未识别到vin');
        }
        return $this->renderSuccess('', $ret['data']['Result']);
        return $this->renderSuccess('', $res['words_result'][0]['words']??'');
    }
    
    public function carInfo()
    {
        $data = $this->postData();
        $car_id = $data['car_id'];
//        $client = new CarModel();
        $res = CarModel::where('id',$car_id)->find();

        //获取品牌logo
        $brand = CarModel::where('name',$res->brand)->find();
        $brand_logo = $brand ? $brand->logo : '';
        $res->brand_logo = $brand_logo;
        //日期修改
        $res->listdate = str_replace('-', '.', $res->listdate);
        return $this->renderSuccess('', $res);
    }
    public function queryLog()
    {
        $user = $this->getUser();
        $data = $this->getData();
        $list = CarQueryLog::where('user_id',$user['user_id'])
            ->with('car')
            ->order('update_time DESC')
            ->paginate($data);
        return $this->renderSuccess('', $list);
    }
}
